#include <stdio.h>
#include <pthread.h>

int global_number = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
bool flag = 0;

void* threadFunc1(void *)
{
    for(int i = 0; i < 200000; ++i)   // 1000万实在太多了，光测试就得等半天，所以少打一个0
    {
        pthread_mutex_lock(&mutex);
        while(flag == 1)          
        {
            pthread_cond_wait(&cond, &mutex);
        }
        ++global_number;
        printf("th1 | global_number = %d, flag = %d\n", global_number, flag);
        flag = 1;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }

    return nullptr;
}

void* threadFunc2(void *)
{
    for(int i = 0; i < 200000; ++i)
    {
        pthread_mutex_lock(&mutex);
        while(flag == 0)
        {
            pthread_cond_wait(&cond, &mutex);
        }
        ++global_number;
        printf("th2 | global_number = %d, flag = %d\n", global_number, flag);
        flag = 0;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }

    return nullptr;

}

void test(){
    pthread_t pthid1, pthid2;
    pthread_create(&pthid1, nullptr, threadFunc1, nullptr);
    pthread_create(&pthid2, nullptr, threadFunc2, nullptr);

    pthread_join(pthid1, nullptr);
    pthread_join(pthid2, nullptr);

    printf("global_number = %d \n", global_number);
    return;
}

int main()
{
    test();
    return 0;
}

